
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution
{
public:
    int sum = 0;
    void dfs(TreeNode *root, int digit)
    {
        int tmp = (digit << 1) + root->val;
        if (!root->left && !root->right)
        {
            sum += tmp;
            return;
        }
        if (root->left)
            dfs(root->left, tmp);
        if (root->right)
            dfs(root->right, tmp);
    }
    int sumRootToLeaf(TreeNode *root)
    {
        dfs(root, 0);
        return sum;
    }
};